package com.lrkj.back.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lrkj.back.Const;
import com.lrkj.back.StartUpOnLoadData;
import com.lrkj.back.entity.TbDepartment;
import com.lrkj.back.entity.TbDict;
import com.lrkj.back.entity.TbPackageMuban;
import com.lrkj.back.entity.ZsDabao;
import com.lrkj.back.entity.TbProduct;
import com.lrkj.back.vo.constant.PathInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lrkj.back.ChineseToEngLetterUtil;
import com.lrkj.back.entity.TbPackageProduct;
import com.lrkj.back.service.TbDepartmentService;
import com.lrkj.back.service.TbDictService;
import com.lrkj.back.service.TbManufactorService;
import com.lrkj.back.service.TbPackageMubanService;
import com.lrkj.back.service.TbPackageProductService;
import com.lrkj.back.service.TbProductService;
import com.lrkj.back.service.TbSeqService;
import com.lrkj.back.service.ZsDabaoService;
import com.lrkj.back.service.ZsShenqingService;
import com.lrkj.back.service.ZsShenqingShoushubaoMingxiService;
import com.lrkj.back.service.ZsShenqingYicipinMingxiService;
import com.lrkj.back.service.ZsWupinBaoFafangService;
import com.lrkj.back.service.ZsWupinFafangService;
import com.lrkj.back.service.ZsWupinYcpFafangService;
import com.lrkj.back.service.ZsYicipinKucunService;
import com.lrkj.back.service.ZsYicipinRukuService;
import cn.com.cbons.mamisay.parent.exception.BusinessException;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;

/**
 * 配置信息 包信息
 */
@Controller
@RequestMapping("/shoushumuban")
public class TbPackageMubanController extends BaseController {

	@Autowired
	private ZsYicipinRukuService yicipinService;
	@Autowired
	private ZsShenqingService shenqingService;
	@Autowired
	private TbManufactorService manufactorService;
	@Autowired
	private ZsShenqingYicipinMingxiService sqmxService;

	@Autowired
	private TbSeqService seqService;
	@Autowired
	private ZsShenqingShoushubaoMingxiService ssbservice;

	@Autowired
	private TbDepartmentService departmentService;
	@Autowired
	private ZsYicipinKucunService kucunService;
	@Autowired
	private TbPackageMubanService mubanservice;
	@Autowired
	private TbSeqService sepservice;
	@Autowired
	private ZsWupinBaoFafangService baofafangservice;
	@Autowired
	private ZsWupinYcpFafangService yicipinfafangservice;
	@Autowired
	private ZsWupinFafangService wupingfafangservice;
	@Autowired
	private TbPackageMubanService ssbmubanservice;
	@Autowired
	private TbPackageProductService ssbxiangxiservice;
	@Autowired
	private TbProductService productservice;
	@Autowired
	private TbPackageProductService baoqixieservice;
	@Autowired
	private ZsDabaoService daobaoservice;
	@Autowired
	private TbDictService tbDictService;
	@Autowired
	private TbDepartmentService tbDepartmentServices;

	//配置--包信息    （店点击查询）
	@RequestMapping("/ssmubanList.do")
	public ModelAndView ssmubanList(String search_Txt, HttpServletRequest request,
			HttpServletResponse response) throws BusinessException{
		Integer pageNo = request.getParameter("pageIndex") == null ? 1 : Integer.valueOf(request.getParameter("pageIndex"));
		Map<String, Object> map = new HashMap<>();
		// 显示下拉
		List<TbDepartment> keshilist = tbDepartmentServices.findAllDepartment();
		request.setAttribute("keshilist", keshilist);
//		if(StringUtils.isNotBlank(tiaojian)) {
//			map.put("baoid", tiaojian);
//		}
		//huichangde kun guotaijunan
		//huataizhengquan
		//zhengquan
		//
		// 选中科室查所有信息
		String packageDepartid = request.getParameter("departmentId");

		map.put("pageNo", pageNo);
		map.put("pageSize", Const.PAGE_SIZE);
		if (StringUtils.isNotBlank(packageDepartid)&&!"0".equals(packageDepartid)) {
			Integer depId = Integer.valueOf(packageDepartid);
			if(depId != PathInfo.depShoushu&&depId != PathInfo.depXiaodu){
//				map.put("packageCategory",1);
				map.put("packageDepartid",packageDepartid);
			}else{
				map.put("packageDepartid", packageDepartid);
			}

		}
		if (StringUtils.isNotBlank(search_Txt)) {
			map.put("packageName", search_Txt);
		}

		// 把分页信息传过去
		PageInfo<TbPackageMuban> page = ssbmubanservice.findAllPackageMuban(map);
		request.setAttribute("shenqingList", page.getList());
		request.setAttribute("packageDepartid", packageDepartid == null ? "" : packageDepartid);
		request.setAttribute("search_Txt", search_Txt == null ? "" : search_Txt);
		request.setAttribute("total", page.getPages());
//		request.setAttribute("tiaojian", tiaojian);
		request.setAttribute("dictMap", StartUpOnLoadData.singleDataMap);
		// 返回到页面
		return new ModelAndView("peizhi/shoushubaoxinxi/shoushubaomuban_records");
	}
	@RequestMapping(value = "/packageAdd.do")
	public ModelAndView packageAdd(
			HttpServletRequest request, HttpServletResponse response) throws BusinessException{
		List<TbDepartment> department = departmentService.findAllDepartment();
		List<ZsDabao> daolist = daobaoservice.selectAllDabao();
		List<TbDict> miejunfangshiList = StartUpOnLoadData.dataListMap.get(StartUpOnLoadData.MIEJUN_KEY);
		List<TbDict> qixieDicts = StartUpOnLoadData.dataListMap.get(StartUpOnLoadData.QXFL);
		request.setAttribute("miejunFangshi", miejunfangshiList);
		request.setAttribute("qixieDicts",qixieDicts);
		request.setAttribute("daolist", daolist);
		request.setAttribute("depList", department);
		request.setAttribute("type",1);
		return new ModelAndView("/peizhi/shoushubaoxinxi/shoushubaomuban_edit");
	}
	
	@RequestMapping(value = "/packageEdit.do")
	public ModelAndView packageEdit(Integer id,String type,
			HttpServletRequest request, HttpServletResponse response) throws BusinessException{
		Integer integer = Integer.valueOf(type);
		if(integer==0){
			List<TbDepartment> department = departmentService.findAllDepartment();
			List<ZsDabao> daolist = daobaoservice.selectAllDabao();
			List<TbDict> miejunfangshiList = StartUpOnLoadData.dataListMap.get(StartUpOnLoadData.MIEJUN_KEY);
			request.setAttribute("miejunFangshi", miejunfangshiList);
			request.setAttribute("daolist", daolist);
			request.setAttribute("depList", department);
			request.setAttribute("id", id == null ? "" : id);
			TbPackageMuban muban = ssbmubanservice.selectByPrimaryKey(String.valueOf(id));
			request.setAttribute("muban", muban);
			return new ModelAndView("/peizhi/shoushubaoxinxi/shoushubaomuban_single_edit");
		}else if(integer==1){
			List<TbDepartment> department = departmentService.findAllDepartment();
			List<ZsDabao> daolist = daobaoservice.selectAllDabao();
			List<TbDict> miejunfangshiList = StartUpOnLoadData.dataListMap.get(StartUpOnLoadData.MIEJUN_KEY);
			request.setAttribute("miejunFangshi", miejunfangshiList);
			request.setAttribute("daolist", daolist);
			request.setAttribute("depList", department);
			request.setAttribute("id", id == null ? "" : id);
			TbPackageMuban muban = ssbmubanservice.selectByPrimaryKey(String.valueOf(id));
			List<TbPackageProduct> mingxiList = baoqixieservice.selectByPackageId(String.valueOf(id));
			request.setAttribute("mingxiList",mingxiList);
			request.setAttribute("muban", muban);
			request.setAttribute("type",type);
			return new ModelAndView("/peizhi/shoushubaoxinxi/shoushubaomuban_edit");
		}
		return null;

	}
	
	

	// 弹出layer手术器械的方法
	@RequestMapping("/qixieDetailList.do")
	public ModelAndView shoushubaoApplyDetailList(String id,String dictId,String changjia,
			HttpServletRequest request, HttpServletResponse response,
			TbPackageMuban TbPackageMuban) throws BusinessException{
		Integer pageNo = request.getParameter("pageIndex") == null ? 1 : Integer.valueOf(request.getParameter("pageIndex"));
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> jsonmap = new HashMap<>();
		Long val = null;
		if (StringUtils.isNotBlank(id)) {
			map.put("productId", id.trim());
			map.put("productName", id.trim());
			map.put("productCode", id.trim());
			map.put("productMark",id.trim());
		}
		if (StringUtils.isNotBlank(changjia)&&!"null".equals(changjia)) {
			val = Long.valueOf(changjia);
			if (val!=0) {//是厂家包
				map.put("protypeIdno", 213);
			}
			if (val==0) {//不是厂家包
				//map.put("protypeIdno", 193);
			}
		}

		if(StringUtils.isNotBlank(dictId)&&!"0".equals(dictId)){
			map.put("protypeRefid2",Integer.valueOf(dictId));
		}
		map.put("pageNo", pageNo);
		map.put("pageSize", Const.PAGE_SIZE);
		PageInfo<TbProduct> page = productservice.findAllProductList(map);

		request.setAttribute("productList", page.getList());
		request.setAttribute("id", id == null ? "" : id);
		request.setAttribute("total", page.getPages());
		List<TbDict> productTypeList = StartUpOnLoadData.dataListMap.get(StartUpOnLoadData.WPFL);
		for (TbProduct pro : page.getList()) {
			jsonmap.put(String.valueOf(pro.getProductId()), pro);
		}
		request.setAttribute("productTypeList",productTypeList);
		request.setAttribute("dictId",dictId);
		request.setAttribute("val", val);
		request.setAttribute("productJson", JSON.toJSON(jsonmap));
		return new ModelAndView("/peizhi/shoushubaoxinxi/shoushuqixie_List");
	}

	// 删除 右边 小器械 异步
	@RequestMapping("/packageQixieDel.do")
	@ResponseBody
	public Map<Object,Object> packageQixieDel(HttpServletRequest request,
			HttpServletResponse response) throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object, Object>();
		try {
			String packageid = request.getParameter("packageid");
			String ids = request.getParameter("id");
			String[] arraId = ids.split(",");
			for (String tid : arraId) {
				TbPackageProduct st = new TbPackageProduct();
				st.setPackageId(packageid);
				st.setProductId(tid);
				ssbxiangxiservice.deleteByPackageQixieMuban(st);
				System.out.println("删除" + tid);

			}
			rtnMap.put("delArr", arraId);
			rtnMap.put("idss", ids);
			rtnMap.put("status", "true");
			rtnMap.put("msg", "删除成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "删除失败");
			e.printStackTrace();
		}
		return rtnMap;
	}

	// 弹出更改界面
	@RequestMapping("/shoushuqixieUpdate.do")
	public ModelAndView shoushuqixieUpdate(String id,
			HttpServletRequest request, HttpServletResponse response,
			TbPackageMuban TbPackageMuban) throws BusinessException{
		Map<String, Object> map = new HashMap<String, Object>();
		int packageid = Integer.parseInt(request.getParameter("packageid"));
		String ids = request.getParameter("id");
		int productId = Integer.parseInt(ids);
		map.put("packageId", packageid);
		map.put("productId", productId);
		List<TbPackageProduct> list = ssbxiangxiservice.findAllPackageProduct(map);
		request.setAttribute("ulist", list);
		return new ModelAndView("/peizhi/shoushubaoxinxi/shoushubaoqixie_edit");
	}

	// 小器械 修改 异步
	@RequestMapping("/shoushuqixieUpdateNum.do")
	@ResponseBody
	public Map<Object,Object> shoushuqixieUpdateNum(HttpServletRequest request,
			HttpServletResponse response) throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object, Object>();
		try {
			String packageid = request.getParameter("packageid");
			String productId = request.getParameter("productId");
			int num = Integer.parseInt(request.getParameter("num"));
			TbPackageProduct st = new TbPackageProduct();
			st.setProductId(productId);
			st.setPackageId(packageid);
			st.setNum(num);
			ssbxiangxiservice.updateQixieMun(st);
			rtnMap.put("status", "true");
			rtnMap.put("msg", "修改成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "修改失败");
			e.printStackTrace();
		}
		return rtnMap;
	}

	// 保存的方法,从页面接收到所有产品的id 和数量,模板的信息，
	@RequestMapping("/packageSave.do")
	@ResponseBody
	@Transactional
	public Map<Object,Object> packageSave(String time,String[] productId, TbPackageMuban muban,
			String[] packNum, HttpServletRequest request,
			HttpServletResponse response) throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<>();
		try {
			List<TbPackageProduct> packageProducts = new ArrayList<>();
//			if (muban.getPackageDepartid()==null) {
//				if (muban.getPackageCategory()==null) {
//					muban.setPackageDepartid(17);
//				}else {
//					muban.setPackageDepartid(16);
//				}
//			}
			if (muban.getPackageDepartid() == 15) {
//				muban.setPackageCategory(null);
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date;
			if(",".equals(time)||"".equals(time)||"undefined".equals(time)){
				date = new Date();
			}else{
				date = sdf.parse(time);
			}

			muban.setPackageCreatetime(date);
			muban.setPackageCode(ChineseToEngLetterUtil.getAllFirstLetter(muban.getPackageName()));
			TbPackageProduct qixieguanlian = null;
			if (productId != null) {
				TbPackageMuban tbPackageMuban = ssbmubanservice.insert(muban);
				TbProduct product = null;
				for (int i = 0; i < productId.length; i++) {
				    product = productservice.selectByPrimaryKey(Integer.valueOf(productId[i]));
					qixieguanlian = new TbPackageProduct();
					qixieguanlian.setPackageId(muban.getPackageId());
					qixieguanlian.setProductId(String.valueOf(product.getProductId()));
					qixieguanlian.setNum(Integer.valueOf(packNum[i]));
					qixieguanlian.setFunction(product.getProductFunction());
					qixieguanlian.setProductName(product.getProductName());
					qixieguanlian.setPackprodCreatetime(new Date());
					packageProducts.add(qixieguanlian);
					// 修改手术包关联表的数据
	//				ssbxiangxiservice.insert(qixieguanlian);
				}
		        ssbxiangxiservice.insertBatch(packageProducts);
				rtnMap.put("status", "true");
				rtnMap.put("package",tbPackageMuban);
				rtnMap.put("msg", "编辑成功");
			}else {
				rtnMap.put("status", "false");
				rtnMap.put("msg", "请添加包器械");
			}
			
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;

	}

	
	// 保存的方法,从页面接收到所有产品的id 和数量,模板的信息，
	@RequestMapping("/packageSingleSave.do")
	@ResponseBody
	public Map<Object,Object> packageSingleSave(TbPackageMuban muban
			) throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<>();
		try {
//			muban.setPackageCreatetime(new Date());
			String name = muban.getPackageName();
			String code = ChineseToEngLetterUtil.getAllFirstLetter(name);
			muban.setPackageCode(code);
			ssbmubanservice.updateByPrimaryKey(muban);
			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;

	}
	// 点击主表删除的方法
	/**
	 * update by win.wu 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/packageDel.do")
	@ResponseBody
	public Map<Object,Object> packageDel(HttpServletRequest request,
			HttpServletResponse response) throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object, Object>();
		try {
			String ids = request.getParameter("id");
			String[] arraId = ids.split(",");
			for (String tid : arraId) {
				ssbmubanservice.deleteByPrimaryKey(tid);
				ssbxiangxiservice.deleteByPackageId(tid);
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "删除成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "删除失败");
			e.printStackTrace();
		}
		return rtnMap;
	}

	// 小表弹出layer手术器械的方法
	@RequestMapping("/shoushuqixieDetailList.do")
	public ModelAndView shoushuqixieDetailList(String id,String dictId,
			HttpServletRequest request, HttpServletResponse response,
			TbPackageMuban TbPackageMuban) throws BusinessException{
		Integer pageNo = request.getParameter("pageIndex") == null ? 1
				: Integer.valueOf(request.getParameter("pageIndex"));
		Map<String, Object> map = new HashMap<>();
//		Map<Integer, Object> jsonmap = new HashMap<Integer, Object>();
		if (StringUtils.isNotBlank(id)) {
			map.put("productId", id.trim());
			map.put("productName", id.trim());
			map.put("productCode", id.trim());
		}
		if(StringUtils.isNotBlank(dictId)&&!"0".equals(dictId)){
			map.put("protypeRefid2",Integer.valueOf(dictId));
		}
		map.put("pageNo", pageNo);
		map.put("pageSize", Const.PAGE_SIZE);
		List<TbDict> productTypeList = StartUpOnLoadData.dataListMap.get(StartUpOnLoadData.WPFL);
		PageInfo<TbProduct> page = productservice.findAllProductList(map);
		request.setAttribute("productList", page.getList());
		request.setAttribute("id", id == null ? "" : id);

		request.setAttribute("total", page.getPages());
//		for (TbProduct pro : page.getList()) {
//			jsonmap.put(pro.getProductId(), pro);
//		}
		String packageId = request.getParameter("gpackid");
//		request.setAttribute("productJson", JSON.toJSON(jsonmap));
		request.setAttribute("dictId",dictId);
		request.setAttribute("productTypeList",productTypeList);
		request.setAttribute("packageId", packageId);
		return new ModelAndView("/peizhi/shoushubaoxinxi/shoushuqixieXiao_list");
	}

	// 点添加到手术包时用到的方法
	@RequestMapping("/qixieSave.do")
	@ResponseBody
	public Map<Object,Object> qixieSave(String[] zhi, String[] numbers,
			HttpServletRequest request, HttpServletResponse response) throws BusinessException{

		Map<Object, Object> rtnMap = new HashMap<Object, Object>();
		Map<String, Object> maptwo = new HashMap<String, Object>();
		// 将查到的手术器械信息，保存到手术包关联表中
		try {
			if (zhi != null) {
				// 如果增加重复的直接在表中改数量，如果是新的则增加
				String baobianhao = request.getParameter("pid");
				for (int i = 0; i < zhi.length; i++) {
					TbPackageProduct packageProduct = new TbPackageProduct();
					TbProduct chanpinProduct = productservice
							.selectByPrimaryKey(Integer.valueOf(zhi[i]));
					packageProduct.setPackageId(baobianhao);
					packageProduct.setProductId(String.valueOf(chanpinProduct
							.getProductId()));
					packageProduct.setProductName(chanpinProduct
							.getProductName());
					packageProduct.setNum(Integer.valueOf(numbers[i]));
					packageProduct.setPackprodCreatetime(new Date());
					maptwo.put("packageId", baobianhao);
					maptwo.put("productId", zhi[i]);
					List<TbPackageProduct> shiyanpinList = ssbxiangxiservice
							.findAllPackageProduct(maptwo);
					if (shiyanpinList.size() > 0) {
						// 有就更改数量 
						TbPackageProduct productTwo = shiyanpinList.get(0);
						productTwo.setNum(productTwo.getNum()
								+ Integer.valueOf(numbers[i]));
						productTwo.setPackprodCreatetime(new Date());
						ssbxiangxiservice.updateByPrimaryKey(productTwo);
					} else {
						// 没有这项就直接添加
						ssbxiangxiservice.insert(packageProduct);
					}
				}

			}

			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}

	// 右边小表点删除时用到的方法
	@RequestMapping("/qixiedelete.do")
	@ResponseBody
	public Map<Object,Object> qixiedelete(String[] zhi, HttpServletRequest request,
			HttpServletResponse response) throws BusinessException{

		Map<Object, Object> rtnMap = new HashMap<Object, Object>();

		// 将查到的手术器械信息，保存到手术包关联表中
		try {

			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}

	//右边显示详细信息的方法,这个是一次品用的
		@RequestMapping("/ssbDetailList.do")
		@ResponseBody
		public Map<Object,Object> ssbDetailList(String id,HttpServletRequest request,
				HttpServletResponse response){
			Map<Object, Object> rtnMap = new HashMap<>();
			try {
				Map<String,Object> map =new HashMap<>();
				if(StringUtils.isNotBlank(id)){
					map.put("shenqingLiushui", id);
				}
				List<TbPackageProduct> mingxiList = baoqixieservice.selectByPackageId(id);
				int num = baoqixieservice.selectNumByPackageId(id);
				rtnMap.put("mxList", mingxiList);
				rtnMap.put("num",num);
				rtnMap.put("packageId", id);
				rtnMap.put("status", "true");
				rtnMap.put("msg", "编辑成功");
			} catch (Exception e) {
				rtnMap.put("status", "false");
				rtnMap.put("msg", "编辑失败");
				e.printStackTrace();
			}
			return rtnMap;
		}
}
